package com.xingfudazi.framework.interceptor.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xingfudazi.common.enums.DBDataStatus;
import com.xingfudazi.common.utils.IdGen;
import com.xingfudazi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 如果没有显式的对通用参数进行赋值，这里会对通用参数进行填充、赋值
 *
 * @author ming
 */
@Slf4j
@Component
public class DefaultDBFieldHandler implements MetaObjectHandler {

    private static final String CREATE_TIME = "createTime";

    private static final String CREATOR = "createBy";

    private static final String UPDATE_TIME = "updateTime";

    private static final String UPDATER = "updateBy";

    private static final String DEL_FLAG = "delFlag";

    private static final String ID = "id";


    @Override
    public void insertFill(MetaObject metaObject) {

        if (getFieldValByName(ID, metaObject) == null
                && judge(ID, metaObject)) {
            this.setFieldValByName(ID, IdGen.nextLongId(), metaObject);
        }

        if (getFieldValByName(CREATE_TIME, metaObject) == null
                && judge(CREATE_TIME, metaObject)) {
            this.setFieldValByName(CREATE_TIME, LocalDateTime.now(), metaObject);
        }

        if (getFieldValByName(CREATOR, metaObject) == null && judge(CREATOR, metaObject)) {
            this.setFieldValByName(CREATOR, SecurityUtils.getLoginUser().getUserId().toString(), metaObject);
        }

        if (getFieldValByName(DEL_FLAG, metaObject) == null && judge(DEL_FLAG, metaObject)) {
            this.setFieldValByName(DEL_FLAG, DBDataStatus.OK.getCode(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (getFieldValByName(UPDATE_TIME, metaObject) == null && judge(UPDATE_TIME, metaObject)) {
            this.setFieldValByName(UPDATE_TIME, LocalDateTime.now(), metaObject);
        }
        if (getFieldValByName(UPDATER, metaObject) == null && judge(UPDATER, metaObject)) {
            this.setFieldValByName(UPDATER, SecurityUtils.getLoginUser().getUserId().toString(), metaObject);
        }
    }

    public boolean judge(String field, MetaObject metaObject) {
        try {
            metaObject.getOriginalObject().getClass().getDeclaredField(field);
        } catch (NoSuchFieldException e) {
            return false;
        }
        return true;
    }
}
 